import * as React from "react";
import * as echarts from 'echarts';
import './index.scss';
import * as moment from 'moment';
import { Link } from "react-router-dom";
import { Form, Row, Col, Input, Button, Icon, DatePicker, Select, Spin, Tabs, Radio } from 'antd';
import { CAMLFilter, CAMLCompare, CamlQuery, SPDataType, CamlParam, CamlOrderBy } from './../../config/CAMLHelper';
import { ListGUID } from '../../config/ListGuid';
import { isHavePermission, isHavePathPermission } from '../../utils/utils'
import store from '../../store/index'
import Api from '../../config/api';
import { dynamicsService } from '../../../../../services/services'
import MinisterDashboard from "../minister-dashboard";
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;

const dateFormat = 'YYYY/MM/DD';
const colorArr = []
interface camlProp {
  params: CamlParam[],
  params1: CamlParam[]
}
export default class Dashboard extends React.Component<any> {
  state = {
    mode: '2',
    ministerLoading: false,
    count: [],
    isLeader: false,
    allData2: [],
    allData1: [],
    allData: [],
    loading: false,
    loading1: false,
    loading2: false,
    //表单数据对象
    form: {
      year: null,
      month: null,
      rangeTime: [],
      reviewer: []
    },
    // 总文件统计 图表数据
    chartData: [
      { value: 0, name: '合同' },
      { value: 0, name: '规章制度' },
      { value: 0, name: '案件管理' },
    ],
    // 当天本人操作 图表数据
    chartDataMySelf: [0, 0, 0, 0, 0, 0, 0, 0, 0],
    // 担当操作比较 图表数据
    chartOperationComparison: [],
    // 审查担当人员列表
    personList: [],
    personInCharge: [],
    totalNum: 0,
    isOpenYear: false,
    isOpenMonth: false,
    isShowChart: false,
    allFileYear: null,
    allFileMonth: null,
    otherInfo: null
  }
  onChange = (e, key) => {
    this.setState({
      form: {
        ...this.state.form,
        [key]: e,

      },
      isOpenYear: false,
      isOpenMonth: false
    })
  }
  onDateOpenChange = (e, type) => {
    if (type === 'year') {
      this.setState({
        isOpenYear: e,
        isOpenMonth: false
      })
    } else {
      this.setState({
        isOpenYear: false,
        isOpenMonth: e
      })
    }
  }

  /**
   * 审查担当人选择
   * @param value 
   */
  onSelectChange = (value) => {
    this.setState({
      form: {
        ...this.state.form,
        reviewer: value
      },
      personInCharge: value

    })
  }
  /**
   * 总文件统计 默认显示当年的数据统计
   */
  async bindAllFileStatistics() {
    this.setState({
      loading: true
    })
    // let params: CamlParam[] = [];
    // if(this.state.form.year || this.state.form.month) {
    //   let {year, month} = {year: this.state.form.year ? this.state.form.year.get('year') : this.state.form.year, month: this.state.form.month ? this.state.form.month.get('month') + 1 : moment().format('MM')+ 1};
    //   let startDate = moment(`${year}-${month >= 10 ? month : '0' + month}`).startOf("month").format("YYYY-MM-DD");
    //   let endDate = moment(`${year}-${month >= 10 ? month : '0' + month}`).endOf("month").format("YYYY-MM-DD");
    //   params.push(new CamlParam("Modified", startDate + "T00:00:00Z", SPDataType.DateTime, CAMLCompare.Geq));
    //   params.push(new CamlParam("Modified", endDate + "T23:59:59Z", SPDataType.DateTime, CAMLCompare.Leq));
    // } else {
    //   params.push(new CamlParam("Modified", moment().startOf('year').format("YYYY-MM-DD") + "T00:00:00Z", SPDataType.DateTime, CAMLCompare.Geq));
    //   params.push(new CamlParam("Modified", moment().endOf('year').format("YYYY-MM-DD") + "T23:59:59Z", SPDataType.DateTime, CAMLCompare.Leq));
    // }
    let { year, month } = { year: this.state.form.year ? this.state.form.year.get('year') : '', month: this.state.form.month ? this.state.form.month.get('month') + 1 : '' };
    // let startDate = moment(`${year}-${month >= 10 ? month : '0' + month}`).startOf("month").format("YYYY-MM-DD");
    // let endDate = moment(`${year}-${month >= 10 ? month : '0' + month}`).endOf("month").format("YYYY-MM-DD");
    let data = await dynamicsService.getPieCount({ year, month })
    // 
    let total = 0;
    let chartData = [];
    for (let i in data.data) {
      chartData.push({
        name: i,
        value: data.data[i]
      })
      total += data.data[i]
    }
    this.setState({
      loading: false,
      chartData,
      totalNum: total
    }, () => {
      this.setChart()
    })

    // this.theQuery(year, month)
    this.setState({
      allFileYear: this.state.form.year,
      allFileMonth: this.state.form.month,
    })
  }
  /**
   * 当天本人操作统计
   */
  async bindOperationByMy() {
    const userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
    let data = await dynamicsService.GetHistogramData({ userName: userinfo.Title });
    let name = [];
    let values = [];
    for (let i in data.data) {
      name.push(i)
      values.push(data.data[i])
    }
    
    this.setState({
      loading1: false,
      chartDataMySelf: values,
    }, () => {
      this.setChart1(name)
    })
    
    // let obj:camlProp = {
    //   params: [],
    //   params1: []
    // };
    // let obj1:camlProp = {
    //   params: [],
    //   params1: []
    // };
    // let obj2:camlProp = {
    //   params: [],
    //   params1: []
    // };
    // let startDate = moment().format("YYYY-MM-DD");
    // let endDate = moment().format("YYYY-MM-DD");
    // obj.params.push(new CamlParam("Modified", startDate + "T00:00:00Z", SPDataType.DateTime, CAMLCompare.Geq));
    // obj.params.push(new CamlParam("Modified", endDate + "T23:59:59Z", SPDataType.DateTime, CAMLCompare.Leq));
    // obj1.params.push(new CamlParam("Modified", startDate + "T00:00:00Z", SPDataType.DateTime, CAMLCompare.Geq));
    // obj1.params.push(new CamlParam("Modified", endDate + "T23:59:59Z", SPDataType.DateTime, CAMLCompare.Leq));
    // obj2.params.push(new CamlParam("Modified", startDate + "T00:00:00Z", SPDataType.DateTime, CAMLCompare.Geq));
    // obj2.params.push(new CamlParam("Modified", endDate + "T23:59:59Z", SPDataType.DateTime, CAMLCompare.Leq));
    // 
    // this.theQuery1(type)
  }
  /**
   * 操作比较
   */
  async bindOperationComparison() {
    this.setState({
      isShowChart: false,
      loading2: true
    })

    let arr = [];
    let users = this.state.personInCharge.length > 0 ? this.state.personInCharge : this.state.personList.map(i => i.userName);
    let rangeTime = this.state.form.rangeTime;
    let startDate = rangeTime.length > 0 ? moment(rangeTime[0]).format("YYYY-MM-DD") : '2000-01-01';
    let endDate = rangeTime.length > 0 ? moment(rangeTime[1]).format("YYYY-MM-DD") : '2099-12-31';
    let data = await dynamicsService.GetLineChatData({ users: users.join('|'), startDate, endDate });
    
    // let s1 = new Date(startDate1 + " 00:00:00").getTime();
    // let e1 = new Date(endDate1 + " 23:59:59").getTime()
    for (let i in data.data) {
      arr.push({
        name: i,
        type: 'line',
        data: data.data[i],
        smooth: true,
      })
    }
    // for(let i = 0; i<users.length; i++) {
    //     arr.push({
    //       name: users[i],
    //       type: 'line',
    //       data: [
    //         data[0].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.ReviewOnID && item.ReviewOnID.includes(users[i]) && item.Names).length,
    //         data[0].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.ReviewOnID && item.ReviewOnID.includes(users[i]) && !item.Names).length,
    //         data[1].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.ReviewOn && item.ReviewOn.includes(users[i]) && item.Names).length,
    //         data[1].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.ReviewOn && item.ReviewOn.includes(users[i]) && !item.Names).length,
    //         data[2].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.Acceptor && item.Acceptor.includes(users[i]) && item.Names).length,
    //         data[2].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.Acceptor && item.Acceptor.includes(users[i]) && !item.Names).length,
    //       ],
    //       smooth: true,
    //   })
    // }
    this.setState({
      chartOperationComparison: arr
    }, () => {
      setTimeout(() => {
        this.setState({
          isShowChart: true,
          loading2: false
        }, () => {
          this.setChart2();
        })
      }, 200)
    })
    // let obj:camlProp = {
    //   params: [],
    //   params1: []
    // };
    // let obj1:camlProp = {
    //   params: [],
    //   params1: []
    // };
    // let obj2:camlProp = {
    //   params: [],
    //   params1: []
    // };
    // let rangeTime = this.state.form.rangeTime;
    //   let startDate = rangeTime.length > 0 ? moment(rangeTime[0]).format("YYYY-MM-DD"): '1979-12-31';
    //   let endDate = rangeTime.length > 0 ? moment(rangeTime[1]).format("YYYY-MM-DD") : '2099-12-31';
    //   obj.params.push(new CamlParam("Modified", startDate + "T00:00:00Z", SPDataType.DateTime, CAMLCompare.Geq));
    //   obj.params.push(new CamlParam("Modified", endDate + "T23:59:59Z", SPDataType.DateTime, CAMLCompare.Leq));
    //   obj1.params.push(new CamlParam("Modified", startDate + "T00:00:00Z", SPDataType.DateTime, CAMLCompare.Geq));
    //   obj1.params.push(new CamlParam("Modified", endDate + "T23:59:59Z", SPDataType.DateTime, CAMLCompare.Leq));
    //   obj2.params.push(new CamlParam("Modified", startDate + "T00:00:00Z", SPDataType.DateTime, CAMLCompare.Geq));
    //   obj2.params.push(new CamlParam("Modified", endDate + "T23:59:59Z", SPDataType.DateTime, CAMLCompare.Leq));
    // if(this.state.form.reviewer) {
    //   this.state.form.reviewer.forEach((item, index) => {
    //     obj.params1.push(new CamlParam("ReviewOnID", item, SPDataType.Text, CAMLCompare.Contains));
    //     obj1.params1.push(new CamlParam("ReviewOn", item, SPDataType.Text, CAMLCompare.Contains));
    //     obj2.params1.push(new CamlParam("Acceptor", item, SPDataType.Text, CAMLCompare.Contains));
    //   })
    // }
    // this.theQuery2(type)
  }
  /**
   * 总文件统计 请求 ListGUID.StandingBook ListGUID.Regulations  ListGUID.CaseManagement  三个list 的数据
   * @param params 传递的参数
   */
  public async theQuery(year, month) {
    // let camlQuery = {
    //   ViewXml: ''
    // }
    // //不排序
    // let demo = Api.buildCamlXml(params);
    // camlQuery.ViewXml = demo;
    // let Naturcontract1 = await Api.GetListItemsByCAMLQuery(ListGUID.StandingBook, camlQuery);
    // let Naturcontract2 = await Api.GetListItemsByCAMLQuery(ListGUID.Regulations, camlQuery);
    // let Naturcontract3 = await Api.GetListItemsByCAMLQuery(ListGUID.CaseManagement, camlQuery);
    // let Natur = await Api.GetListItemsByCAMLQuery('69cce834-b2cb-4f47-9b66-9b8d9d36b330', camlQuery)
    // let newNatur = await Api._getListFileData({ListGUID: '4c4e8239-4913-4cf7-8491-43e0771aacaa'})

    let Naturcontract1 = await Api._getLibraryFileData({ ListGUID: ListGUID.ContractLib })
    let Naturcontract2 = await Api._getLibraryFileData({ ListGUID: ListGUID.RegulationsLib })
    let Naturcontract3 = await Api._getLibraryFileData({ ListGUID: ListGUID.CaseLib })
    let Naturcontract4 = await Api._getLibraryFileData({ ListGUID: ListGUID.CommonLib })
    let Naturcontract5 = await Api._getLibraryFileData({ ListGUID: ListGUID.ContractPetitionLib })
    let Naturcontract6 = await Api._getLibraryFileData({ ListGUID: ListGUID.RegulationsPetitionLib })
    let aa = dynamicsService.getPieCount({ year, month })
    
    let array = []
    // return
    // Naturcontract1.forEach(async element => {

    //   if (element.FileAddress != null) {
    //     for (let jay = 0; jay < Naturcontract1.length; jay++) {
    //       // 
    //       if (Naturcontract1[jay].FSObjType == 1 && Naturcontract1[jay].FileRef.indexOf(element.FileAddress) != -1 && Naturcontract1[jay].Folder.ItemCount == 0) {
    //         array.push(element)
    //       }
    //     }
    //   }
    // })
    
    this.setState({
      allData: [Naturcontract1, Naturcontract2, Naturcontract3, Naturcontract4, Naturcontract5, Naturcontract6]
    }, () => {
      // if(type === 1) {
      //   this.setData('chartData', [Naturcontract1,Naturcontract2,Naturcontract3,Naturcontract4,Naturcontract5,Naturcontract6])
      // }
    })
    store.dispatch({ type: 'chartData', data: [Naturcontract1, Naturcontract2, Naturcontract3, Naturcontract4, Naturcontract5, Naturcontract6] });

    this.setState({
      allFileYear: this.state.form.year,
      allFileMonth: this.state.form.month,
    })
  }

  /**
   * 当天本人操作获取list数据
   * 参数大体相同，只有审查担当id 不同
   * @param s 开始时间
   * @param e 结束时间
   */
  public async theQuery1(type) {
    // let camlQuery = { ViewXml: '' }
    // let demo = Api.buildCamlXmlForCurrentOperator(obj.params, obj.params1);
    // camlQuery.ViewXml = demo;

    // let camlQuery1 = { ViewXml: '' }
    // let demo1 = Api.buildCamlXmlForCurrentOperator(obj1.params, obj1.params1);
    // camlQuery1.ViewXml = demo1;

    // let camlQuery2 = { ViewXml: '' }
    // let demo2 = Api.buildCamlXmlForCurrentOperator(obj2.params, obj2.params1);
    // camlQuery2.ViewXml = demo2;
    let Naturcontract1 = await Api._getPagedNext({ Guid: ListGUID.StandingBook, select: 'Id, ReviewOnID, Modified, Created' });
    let Naturcontract2 = await Api._getPagedNext({ Guid: ListGUID.Regulations, select: 'Id, ReviewOn, Modified, Created' });
    let Naturcontract3 = await Api._getPagedNext({ Guid: ListGUID.CaseManagement, select: 'Id, Acceptor, Modified, Created' });
    this.setState({
      allData1: [Naturcontract1, Naturcontract2, Naturcontract3]
    }, () => {
      if (type === 1) {
        this.setData('chartDataMySelf', [Naturcontract1, Naturcontract2, Naturcontract3])
      }

    })
    store.dispatch({ type: 'chartDataMySelf', data: [Naturcontract1, Naturcontract2, Naturcontract3] });
  }

  /**
   * 担当操作比较数据查询
   */
  public async theQuery2(type) {

    // let camlQuery = { ViewXml: '' }
    // let demo = Api.buildCamlXmlForCurrentOperator(obj.params, obj.params1);
    // camlQuery.ViewXml = demo;

    // let camlQuery1 = { ViewXml: '' }
    // let demo1 = Api.buildCamlXmlForCurrentOperator(obj1.params, obj1.params1);
    // camlQuery1.ViewXml = demo1;

    // let camlQuery2 = { ViewXml: '' }
    // let demo2 = Api.buildCamlXmlForCurrentOperator(obj2.params, obj2.params1);
    // camlQuery2.ViewXml = demo2;
    let Naturcontract1 = await Api._getPagedNext({ Guid: ListGUID.StandingBook, select: 'Id, ReviewOnID, Modified, Created, Names' });
    let Naturcontract2 = await Api._getPagedNext({ Guid: ListGUID.Regulations, select: 'Id, ReviewOn, Modified, Created, Names' });
    let Naturcontract3 = await Api._getPagedNext({ Guid: ListGUID.CaseManagement, select: 'Id, Acceptor, Modified, Created, Names' });
    this.setState({
      allData2: [Naturcontract1, Naturcontract2, Naturcontract3]
    }, () => {
      if (type === 1) {
        this.setData('chartOperationComparison', [Naturcontract1, Naturcontract2, Naturcontract3])
      }

    })
    store.dispatch({ type: 'chartOperationComparison', data: [Naturcontract1, Naturcontract2, Naturcontract3] });


  }
  handleModeChange = e => {
    const mode = e.target.value;
    
    this.setState({ mode });
  };
  public render(): React.ReactElement {
    return (
      <div className="dashBox">
        {
           this.state.isLeader && <Radio.Group onChange={this.handleModeChange} value={this.state.mode} style={{ marginBottom: 8 }}>
            <Radio.Button value="2">台账统计</Radio.Button>
            <Radio.Button value="1">汇总统计</Radio.Button>
          </Radio.Group>
        }
        {
          this.state.isLeader && <div className="empty"></div>
        }
        
        <Tabs defaultActiveKey={this.state.mode} activeKey={this.state.mode} className='dasTab'>

          {
           this.state.isLeader && <TabPane tab='台账统计' key='2'><div className='main-body'>
              <div className="chart-flex">
                <div className="chart">

                  <div className="chart-title">
                    统计数据
                  </div>
                  <div className="line"></div>
                  <Row>
                    <Col span={8}>
                      <Form.Item label='年'>
                        <DatePicker allowClear placeholder="请选择年份" value={this.state.form.year} open={this.state.isOpenYear} format="YYYY" mode='year' onOpenChange={(e) => this.onDateOpenChange(e, 'year')} onPanelChange={(e) => this.onChange(e, 'year')} onChange={(e) => this.onChange(e, 'year')} />
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item label='月'>
                        <DatePicker allowClear placeholder="请选择月份" value={this.state.form.month} open={this.state.isOpenMonth} format="MM" mode='month' onOpenChange={(e) => this.onDateOpenChange(e, 'month')} onPanelChange={(e) => this.onChange(e, 'month')} onChange={(e) => this.onChange(e, 'month')} />
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item>
                        {
                          isHavePermission('Dashboard/searchtotal') ? <Button type="primary" onClick={() => this.bindAllFileStatistics()}>筛选</Button> : null
                        }

                      </Form.Item>
                    </Col>
                  </Row>
                  <div style={{ position: 'relative' }}>
                    <Spin spinning={this.state.loading} style={{ position: 'absolute', left: '0', right: '0', top: '40%' }} />
                    <div id="chart" className="chart-box"></div>
                    <div className="total-num">
                      {this.state.allFileYear ? this.state.allFileYear.get('year') + '年' : null}{this.state.allFileMonth ? this.state.allFileMonth.get('month') + 1 + '月' : null}统计数据： <span>{this.state.totalNum}</span>
                    </div>
                  </div>

                </div>
                <div className="chart">
                  <div className="chart-title">
                    当天本人操作
                  </div>
                  <div className="line"></div>

                  <Spin spinning={this.state.loading1} style={{ position: 'absolute', left: '0', right: '0', top: '40%' }} />
                  <div id="chart1" className="chart-box" style={{ height: '270px', marginTop: '40px' }}>

                  </div>
                </div>
              </div>
              <div className="chart-flex">
                <div className="chart" style={{ height: '390px' }}>
                  <div className="chart-title" style={{ margin: '1% 0px' }}>
                    担当操作比较
                  </div>
                  <div className="line" style={{ marginBottom: '.78%' }}></div>
                  <Row style={{ position: 'absolute', width: '100%' }}>
                    <Col span={8}>
                      <Form.Item label="审查担当">
                        <Select allowClear
                          showSearch
                          placeholder="请选择审查担当人"
                          optionFilterProp="children"
                          onChange={this.onSelectChange}
                          style={{ width: '100%' }}
                          mode="multiple"
                        >
                          {
                            this.state.personList.map(element => {
                              return <Option value={element.userName}>{element.userName}</Option>
                            })
                          }
                        </Select>
                      </Form.Item>

                    </Col>
                    <Col span={8}>
                      <Form.Item label="日期范围">
                        <RangePicker allowClear
                          onChange={(e) => this.onChange(e, 'rangeTime')}
                          placeholder={['选择开始日期', '选择结束日期']}
                          format={dateFormat}
                        />
                      </Form.Item>
                    </Col>
                    <Col span={1}>
                      <Form.Item>
                        {
                          isHavePermission('Dashboard/searchcurrent') ? <Button type="primary" onClick={() => this.bindOperationComparison()}>筛选</Button> : null
                        }

                      </Form.Item>
                    </Col>
                  </Row>
                  <Spin spinning={this.state.loading2} style={{ position: 'absolute', left: '0', right: '0', top: '40%' }} />
                  {this.state.isShowChart ? <div id="chart2" className="chart-box" style={{ height: '290px', marginTop: '50px' }}></div> : null}

                </div>
              </div>
            </div></TabPane>
          }
          <TabPane tab='汇总统计' key='1'><Spin spinning={this.state.ministerLoading}><MinisterDashboard datacount={this.state.count}></MinisterDashboard></Spin></TabPane>
        </Tabs>



      </div>


    );
  }
  setData = (type, data1) => {
    let data = JSON.parse(JSON.stringify(data1))
    switch (type) {
      case 'chartData':
        
        let { year, month } = { year: this.state.form.year ? this.state.form.year.get('year') : '', month: this.state.form.month ? this.state.form.month.get('month') + 1 : '' };
        if (year) {
          data[0] = data[0].filter(item => moment(item.Created).get('year') === year);
          data[1] = data[1].filter(item => moment(item.Created).get('year') === year);
          data[2] = data[2].filter(item => moment(item.Created).get('year') === year);
          data[3] = data[3].filter(item => moment(item.Created).get('year') === year);
          data[4] = data[4].filter(item => moment(item.Created).get('year') === year);
          data[5] = data[5].filter(item => moment(item.Created).get('year') === year);
        }
        if (month) {
          data[0] = data[0].filter(item => moment(item.Created).get('month') + 1 === month);
          data[1] = data[1].filter(item => moment(item.Created).get('month') + 1 === month);
          data[2] = data[2].filter(item => moment(item.Created).get('month') + 1 === month);
          data[3] = data[3].filter(item => moment(item.Created).get('month') + 1 === month);
          data[4] = data[4].filter(item => moment(item.Created).get('month') + 1 === month);
          data[5] = data[5].filter(item => moment(item.Created).get('month') + 1 === month);

        }
        this.setState({
          loading: false,
          chartData: [
            { value: data[0].length, name: '合同' },
            { value: data[1].length, name: '规章制度' },
            { value: data[2].length, name: '案件管理' },
            { value: data[3].length, name: '通用文档' },
            { value: data[4].length, name: '合同申请书' },
            { value: data[5].length, name: '规章制度申请书' },
          ],
          totalNum: data[0].length + data[1].length + data[2].length + data[3].length + data[4].length + data[5].length
        }, () => {
          this.setChart()
        })

        break;
      case 'chartDataMySelf':
        
        let startDate = moment().format("YYYY-MM-DD");
        let endDate = moment().format("YYYY-MM-DD");
        let s = new Date(startDate + " 00:00:00").getTime();
        let e = new Date(endDate + " 23:59:59").getTime()
        // (new Date(i.Modified).getTime() >= s && new Date(i.Modified).getTime() <= e)
        this.setState({
          loading1: false,
          chartDataMySelf: [
            data[0].filter(i => moment(s).format('YYYY-MM-DD') === moment(i.Modified).format('YYYY-MM-DD') && i.ReviewOnID && this.state.otherInfo && i.ReviewOnID.includes(this.state.otherInfo.userName)).length,
            data[1].filter(i => moment(s).format('YYYY-MM-DD') === moment(i.Modified).format('YYYY-MM-DD') && i.ReviewOn && this.state.otherInfo && i.ReviewOn.includes(this.state.otherInfo.userName)).length,
            data[2].filter(i => moment(s).format('YYYY-MM-DD') === moment(i.Modified).format('YYYY-MM-DD') && i.Acceptor && this.state.otherInfo && i.Acceptor.includes(this.state.otherInfo.userName)).length,
          ],
        }, () => {
          // this.setChart1()
        })

        break;
      case 'chartOperationComparison':
        this.setState({
          isShowChart: false,
        })
        let arr = [];
        let users = this.state.personInCharge.length > 0 ? this.state.personInCharge : this.state.personList.map(i => i.userName);
        let rangeTime = this.state.form.rangeTime;
        let startDate1 = rangeTime.length > 0 ? moment(rangeTime[0]).format("YYYY-MM-DD") : '2000-01-01';
        let endDate1 = rangeTime.length > 0 ? moment(rangeTime[1]).format("YYYY-MM-DD") : '2099-12-31';
        let s1 = new Date(startDate1 + " 00:00:00").getTime();
        let e1 = new Date(endDate1 + " 23:59:59").getTime()
        for (let i = 0; i < users.length; i++) {
          arr.push({
            name: users[i],
            type: 'line',
            data: [
              data[0].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.ReviewOnID && item.ReviewOnID.includes(users[i]) && item.Names).length,
              data[0].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.ReviewOnID && item.ReviewOnID.includes(users[i]) && !item.Names).length,
              data[1].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.ReviewOn && item.ReviewOn.includes(users[i]) && item.Names).length,
              data[1].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.ReviewOn && item.ReviewOn.includes(users[i]) && !item.Names).length,
              data[2].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.Acceptor && item.Acceptor.includes(users[i]) && item.Names).length,
              data[2].filter(item => new Date(item.Created).getTime() >= s1 && new Date(item.Created).getTime() <= e1 && item.Acceptor && item.Acceptor.includes(users[i]) && !item.Names).length,
            ],
            smooth: true,
          })
        }
        this.setState({
          chartOperationComparison: arr
        }, () => {
          setTimeout(() => {
            this.setState({
              isShowChart: true,
              loading2: false
            }, () => {
              this.setChart2();
            })
          }, 200)
        })

        break
    }
  }
  async componentDidMount() {
    let leaderUpers = JSON.parse(sessionStorage.getItem('AADUsers'));
    let userPer = leaderUpers.filter(i => i.mail === JSON.parse(sessionStorage.getItem('userInfo')).Email);
    let isLeader = false;
    
    if(userPer.length > 0 && userPer[0].department === '法務部') {
      isLeader = true
      this.setState({
        isLeader: true
      })
    }
    for (let i = 0; i < 100; i++) {
      colorArr.push(this.randomHexColor())
    }
    isHavePathPermission();
    this.setState({
      ministerLoading: true,
    })
    if(isLeader) {
      this.setState({
        loading: true,
        loading1: true,
        loading2: true
      })
    }
    let data = await dynamicsService.GetPetitionMonth({email: JSON.parse(sessionStorage.getItem('userInfo')).Email});
    let count = [];
    for (let i in data.data) {
      count.push({
        label: i,
        value: data.data[i].Count,
        data: data.data[i].Dept,
        Total: data.data[i].Total
      })
    }
    this.setState({
      count,
      ministerLoading: false,
      mode: isLeader ? '2' : '1'
    }, () => {
      
    })
    
    if (isLeader) {
      this.getPersonList()
      this.setState({
        loading: true,
        loading1: true,
        loading2: true
      })
      setTimeout(() => {
        this.bindAllFileStatistics()
        this.bindOperationByMy()
        this.bindOperationComparison()

      }, 500);
    }
    

  }
  randomHexColor() {
    return "rgb(" + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + ")"
  }
  async getPersonList() {
    let personList = await Api._getListData({ ListGUID: ListGUID.ReviewOn });
    let names = [];
    const userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
    const userList = JSON.parse(localStorage.getItem('usersList'));
    personList = personList.filter(i => !i.Title.includes('-历史') && i.Title !== '刘玉梅测试' && i.Title !== 'demo22' && i.Title !== 'demo21')
    personList.sort((x, y) => x.Title.localeCompare(y.Title, 'zh-Hans-CN'))
    
    for (let i = 0; i < personList.length; i++) {
      
      let user = userList.filter(j => j.Id === personList[i].ReviewUserId);
      let user1 = user.length > 0 ? user[0] : null
      if (user1) {
        personList[i].userName = user1.Title;
        names.push(user1.Title)
        if (personList[i].userName === userinfo.Title) {
          this.setState({
            otherInfo: personList[i]
          })
        }
      }
    }
    // personList.forEach(async element => {
    //   // let user = await Api.GetUserById(element.ReviewUserId);
    //   let user = userList.filter(i => i.Id === element.ReviewUserId);
    //   let user1 = user.length > 0 ? user[0] : null
    //   if(user1) {
    //     element.userName = user1.Title;
    //     names.push(user1.Title)
    //     if(element.userName === userinfo.Title) {
    //       this.setState({
    //         otherInfo: element
    //       })
    //     }
    //   }

    // });
    this.setState({
      personList: personList,
      personInCharge: names
    }, () => {
      
    })
  }
  setChart() {
    var chartDom = document.getElementById('chart');
    var myChart = echarts.init(chartDom);
    var option;
    option = {
      tooltip: {
        trigger: 'item'
      },
      color: ['#2C93EE', '#EC9E1F', '#7EE120', '#39b54a', '#e03997', '#6739b6'],
      legend: {
        top: '10%',
        left: '5%',
        orient: 'vertical'
      },

      series: [
        {
          name: '总数统计',
          type: 'pie',
          radius: '70%',
          center: ["70%", "50%"],
          label: {
            formatter: "{d|{c}} \n\r {b|{b}}",
            rich: {
              d: {
                color: '#2C93EE',
                // color: 'auto',
                fontSize: 16,
                lineHeight: 20
              },
              b: {
                color: '#666666',
                fontSize: 14,
                lineHeight: 20
              }
            },
          },

          data: this.state.chartData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    window.addEventListener('resize', function () {
      // 让我们的图表调用 resize这个方法
      myChart.resize();
    });
    option && myChart.setOption(option);
  }
  setChart1(name) {
    var chartDom = document.getElementById('chart1');
    var myChart = echarts.init(chartDom);
    var option;
    option = {
      color: ['#2C93EE', '#EC9E1F', '#7EE120'],
      grid: {
        left: "5%",
        top: "10%",
        right: "5%",
        bottom: "10%"
      },
      xAxis: {
        type: 'category',
        data: name
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: this.state.chartDataMySelf,
          type: 'bar',
          showBackground: true,
          barWidth: 20,
          label: {
            show: true,
            position: 'top'
          },
        }
      ]
    };
    window.addEventListener('resize', function () {
      // 让我们的图表调用 resize这个方法
      myChart.resize();
    });
    option && myChart.setOption(option);
  }
  setChart2() {
    
    var chartDom = document.getElementById('chart2');
    var myChart = echarts.init(chartDom);
    var option;
    option = {
      color: colorArr,
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        left: "5%",
        top: "15%",
        right: "5%",
        bottom: "10%"
      },
      legend: {
        data: this.state.personInCharge.length > 0 ? this.state.personInCharge : this.state.personList.map(i => i.userName),
        left: '0%'
      },
      xAxis: {
        type: 'category',
        data: ['合同编号', '无文件合同编号', '规定制度编号', '无文件规定制度编号', '案件编号', '无文件案件编号']
      },
      yAxis: {
        type: 'value'
      },
      series: this.state.chartOperationComparison
    };
    window.addEventListener('resize', function () {
      // 让我们的图表调用 resize这个方法
      myChart.resize();
    });
    option && myChart.setOption(option);
  }
}
